'use client';

import { useState, useEffect } from 'react';
import { FamilyMember, FamilyTreeNode } from '../types/family';
import { convertToAncientNumber } from '../types/ancientNumberMap';
import { generatePDF } from '../utils/pdfGenerator';

interface ListViewProps {
  familyData: FamilyMember[];
}

export default function ListView({ familyData }: ListViewProps) {
  const [expandedNodes, setExpandedNodes] = useState<Set<string>>(new Set());

  if (familyData.length === 0) {
    return (
      <div className="flex items-center justify-center h-64">
        <p className="text-gray-500 text-lg">暂无族谱数据，请先添加成员</p>
      </div>
    );
  }

  // 构建树形结构
  const buildTree = (data: FamilyMember[]): FamilyTreeNode[] => {
    const nodeMap = new Map<string, FamilyTreeNode>();

    // 创建所有节点
    data.forEach(person => {
      nodeMap.set(person.id, { ...person, children: [] });
    });

    const roots: FamilyTreeNode[] = [];

    // 建立父子关系
    data.forEach(person => {
      const node = nodeMap.get(person.id)!;
      if (person.parentId && nodeMap.has(person.parentId)) {
        const parent = nodeMap.get(person.parentId)!;
        parent.children.push(node);
      } else {
        roots.push(node);
      }
    });

    return roots;
  };

  const treeData = buildTree(familyData);

  // 默认展开所有节点
  useEffect(() => {
    const allNodeIds = new Set<string>();
    const collectNodeIds = (nodes: FamilyTreeNode[]) => {
      nodes.forEach(node => {
        if (node.children.length > 0) {
          allNodeIds.add(node.id);
          collectNodeIds(node.children);
        }
      });
    };
    collectNodeIds(treeData);
    setExpandedNodes(allNodeIds);
  }, [familyData]); // 当familyData变化时重新计算

  // 切换节点展开/折叠状态
  const toggleNode = (nodeId: string) => {
    const newExpanded = new Set(expandedNodes);
    if (newExpanded.has(nodeId)) {
      newExpanded.delete(nodeId);
    } else {
      newExpanded.add(nodeId);
    }
    setExpandedNodes(newExpanded);
  };

  // 递归渲染树形结构
  const renderTreeNode = (node: FamilyTreeNode, level: number = 0): JSX.Element[] => {
    const elements: JSX.Element[] = [];
    const isExpanded = expandedNodes.has(node.id);
    const hasChildren = node.children.length > 0;

    // 添加当前节点
    elements.push(
      <div key={node.id} className="flex items-center py-1 hover:bg-gray-50 rounded">
        <div style={{ marginLeft: `${level * 20}px` }} className="flex items-center">
          {hasChildren ? (
            <button
              onClick={() => toggleNode(node.id)}
              className="mr-2 w-4 h-4 flex items-center justify-center text-gray-500 hover:text-gray-700 focus:outline-none"
            >
              {isExpanded ? '▼' : '▶'}
            </button>
          ) : (
            <span className="mr-2 w-4 h-4 flex items-center justify-center text-gray-400">
              {level > 0 && '•'}
            </span>
          )}
          <span className={`font-medium ${(node.gender || 'male') === 'male' ? 'text-blue-600' : 'text-pink-600'
            }`}>
            {node.name}
          </span>
          <span className="text-gray-500 text-sm ml-2">
            ({(node.gender || 'male') === 'male' ? '男' : '女'}, 第{convertToAncientNumber(node.generation)}世)
          </span>
          {hasChildren && (
            <span className="text-gray-400 text-xs ml-2">
              [{node.children.length}个子女]
            </span>
          )}
        </div>
      </div>
    );

    // 如果展开且有子节点，递归添加子节点
    if (isExpanded && hasChildren) {
      node.children.forEach(child => {
        elements.push(...renderTreeNode(child, level + 1));
      });
    }

    return elements;
  };

  // 展开所有节点的函数
  const expandAll = () => {
    const allNodeIds = new Set<string>();
    const collectNodeIds = (nodes: FamilyTreeNode[]) => {
      nodes.forEach(node => {
        if (node.children.length > 0) {
          allNodeIds.add(node.id);
          collectNodeIds(node.children);
        }
      });
    };
    collectNodeIds(treeData);
    setExpandedNodes(allNodeIds);
  };

  // 折叠所有节点的函数
  const collapseAll = () => {
    setExpandedNodes(new Set());
  };

  // 下载PDF
  const downloadPDF = async () => {
    try {
      await generatePDF('listview-content', {
        filename: '族谱目录层级.pdf',
        orientation: 'portrait',
        format: 'a4'
      });
    } catch (error) {
      alert('PDF生成失败，请重试');
    }
  };

  return (
    <div className="p-6">
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-2xl font-bold text-secondary">目录层级</h2>
        <div className="space-x-2">
          <button
            onClick={expandAll}
            className="px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors"
          >
            展开所有
          </button>
          <button
            onClick={collapseAll}
            className="px-3 py-1 text-sm bg-gray-500 text-white rounded hover:bg-gray-600 transition-colors"
          >
            折叠所有
          </button>
          <button
            onClick={downloadPDF}
            className="px-3 py-1 text-sm bg-green-500 text-white rounded hover:bg-green-600 transition-colors"
          >
            下载PDF
          </button>
        </div>
      </div>
      <div id="listview-content" className="bg-white border border-gray-200 rounded-lg p-6">
        <div className="text-sm leading-relaxed">
          {treeData.map(root => renderTreeNode(root)).flat()}
        </div>
      </div>
    </div>
  );
}